// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    //蓝牙运行情况
    bluetoothruns:[],
    bluetoothdeviceslist:[]
  },
  // 事件处理函数



  /*====蓝牙辅助工具类====*/
  // ArrayBuffer转16进度字符串示例
  _ab2hex(buffer) {
    var array = []
    var dv = new DataView(buffer);
    for(var i=0;i<dv.byteLength;i++){ 
       var data = dv.getUint8(i);
       array[i] = this.int2hex(data,2) 
    }
    if(array.length > 0){
        var notifyValue = wx.getStorageSync('notifyValue')
        // console.log("notifyValue++"+notifyValue)
        notifyValue =notifyValue && notifyValue.length > 0 ? notifyValue.concat(array) : array    
        wx.setStorageSync('notifyValue', notifyValue)
      
    }else{
      wx.getStorageSync('notifyValue') && wx.clearStorage('notifyValue')
    }
    // console.log("array-----"+array)
    return array;
  },
  int2hex(num, width,type) {//十六进制
    var hex = "0123456789abcdef";
    var s = "";
    while (num) {
      s = hex.charAt(num % 16) + s;
      num = Math.floor(num / 16);
    }
    if (typeof width === "undefined" || width <= s.length) {
      return "0x" + s;
    }
    var delta = width - s.length;
    var padding = "";
    while(delta-- > 0) {
      padding += "0";
    }
    return "0x" + padding + s;
  },



  /*====蓝牙====↓
  https://blog.csdn.net/qq_43799179/article/details/126751176
  */
  openBluetoothAdapter(){
    return new Promise((res,rej)=>{
      wx.openBluetoothAdapter({
        success:resv=>{
          res({'openBluetoothAdapter':resv})
        },
        fail:error=>{
          rej({'openBluetoothAdapter':0})
        }
      })
    })
  },
  getBluetoothAdapterState(){
    return new Promise((res,rej)=>{
      wx.getBluetoothAdapterState({
        success:resv=>{
          res({'getBluetoothAdapterState':resv})
        },
        fail:error=>{
          rej({'getBluetoothAdapterState':0})
        }
      })
    })
  },
  startBluetoothDevicesDiscovery(){
    return new Promise((res,rej)=>{
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        interval:0,
        success:resv=>{
          res({'startBluetoothDevicesDiscovery':resv})
        },
        fail:error=>{
          rej({'startBluetoothDevicesDiscovery':0})
        }
      })
    })
  },
  onBluetoothDeviceFound(){
    return  new Promise((res,rej)=>{
      wx.onBluetoothDeviceFound((resv) => {
        res({'onBluetoothDeviceFound':resv})
      })
    })
  },
  createBLEConnection(deviceId){
    return new Promise((res,rej)=>{
      wx.createBLEConnection({
        deviceId: deviceId,
        success:resv=>{
          res({'createBLEConnection':1})
        },
        fail:error=>{
          rej({'createBLEConnection':0})
        }
      })
    })
  },
  getBLEDeviceServices(deviceId){
    return new Promise((res,rej)=>{
      wx.getBLEDeviceServices({
        deviceId: deviceId,
        success:resv=>{
          res({'getBLEDeviceServices':1})
        },
        fail:error=>{
          rej({'getBLEDeviceServices':0})
        }
      })
    })
  },

  //
  
  searchbluetooth(res){
    var getresv = (resv)=>{
      var temp = resv.onBluetoothDeviceFound.devices
      for(var i=0;i<temp.length;i++){
        if(temp[i]){
          temp[i].advertisData = this._ab2hex(temp[i].advertisData)
          temp[i].strobj = JSON.stringify(temp[i])
        }
      }
      this.setData({bluetoothdeviceslist:[]})
      setTimeout(()=>{
        this.setData({bluetoothdeviceslist:temp})
      })
    };
    getresv(res);
    var fn = ()=>{
      setTimeout(()=>{
        this.onBluetoothDeviceFound()
        .then(resv =>{
          getresv(resv)
          fn()
        })
        .catch(error=>{
          fn()
        })
      },2000)
    }
    fn()
  },


  bluetooth(){
    this.openBluetoothAdapter().then(res=>{
      var temp = this.data.bluetoothruns
      temp.push('openBluetoothAdapter')
      this.setData({'bluetoothruns':temp})
      return this.getBluetoothAdapterState()
    }).then((res)=>{
      var temp = this.data.bluetoothruns
      temp.push('getBluetoothAdapterState')
      this.setData({'bluetoothruns':temp})
      return this.startBluetoothDevicesDiscovery()
    }).then((res)=>{
      var temp = this.data.bluetoothruns
      temp.push('startBluetoothDevicesDiscovery')
      this.setData({'bluetoothruns':temp})
      return this.onBluetoothDeviceFound()
    }).then((res)=>{
      var temp = this.data.bluetoothruns
      temp.push('onBluetoothDeviceFound')
      this.setData({'bluetoothruns':temp})
      this.searchbluetooth(res)
    }).catch((error)=>{
      console.log(error)
    })
  },



  /*====蓝牙====↑*/

  onLoad() {
    this.bluetooth()//蓝牙初始化
  },

})
